package com.newenergy.wisehome.config;

import android.app.Application;
import android.content.Context;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.newenergy.light.ble.AdvertiserManager;
import com.newenergy.wisehome.common.MyEvent;
import com.newenergy.wisehome.common.helper.LogHelper;
import com.newenergy.wisehome.common.helper.SPUtil;
import com.newenergy.wisehome.common.helper.ToastUtil;
import com.newenergy.wisehome.common.util.DensityUtils;
import com.newenergy.wisehome.common.util.ImageUtil;
import com.newenergy.wisehome.gateway.common.BLUserInfoUnits;
import com.newenergy.wisehome.gateway.manager.BLLocalFamilyManager;
import com.newenergy.wisehome.receiver.NetWorkReceiver;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;

import cn.com.broadlink.account.BLAccount;
import cn.com.broadlink.base.BLConfigParam;
import cn.com.broadlink.family.BLFamily;
import cn.com.broadlink.sdk.BLLet;
import me.yokeyword.fragmentation.Fragmentation;

public class BaseApp extends Application {

    public static BaseApp instance;

    //网络监听广播
    private NetWorkReceiver mNetWorkReceiver;
    //表示是否连接
    public static boolean isConnected;
    //表示网络类型（移动数据或者wifi）移动：Moblie Wifi:Wifi
    public static String netWorkState;

   /* public static RefWatcher getRefWatcher(Context context) {
        BaseApp application = (BaseApp) context.getApplicationContext();
        return application.refWatcher;
    }
    private RefWatcher refWatcher;*/

    public static BLUserInfoUnits mBLUserInfoUnits;


    @Override
    public void onCreate() {
        super.onCreate();
        init();
        mBLUserInfoUnits = new BLUserInfoUnits(this);
        BLLocalFamilyManager blFamilyManager = BLLocalFamilyManager.getInstance();
        blFamilyManager.initContext(getApplicationContext());
        initFragmentation();
        initBLSdk();
        blFamilyManager.login();

    }


    private void initFragmentation() {
        Fragmentation.builder()
                // 设置 栈视图 模式为 BUBBLE（默认）悬浮球模式   SHAKE: 摇一摇唤出  NONE：隐藏， 仅在Debug环境生效
                .stackViewMode(Fragmentation.NONE)
                .debug(true) // 实际场景建议.debug(BuildConfig.DEBUG)
                .handleException(e -> {
                })
                .install();
    }



    private void init() {
        instance = this;
        LogHelper.setLEVEL(2);
        LogHelper.isShow = true;
        ToastUtil.init(this);
        SPUtil.init(this);
        SPUtil.put(Constants.ISDOWNLOAD,false);
        ImageUtil.init(getApplicationContext());
        /*****网络状态监听********/
        netWorkReceiver();
        DensityUtils.init(this);
        AdvertiserManager.getInstance().setContext(this);

        //初始化LeakCanary
      /*  if (LeakCanary.isInAnalyzerProcess(this)) {
            return;
        }
        refWatcher=LeakCanary.install(this);*/

    }

    /**
     * 网络状态广播注册
     * @author hjy
     * created at 2016/12/12 15:30
     */
    private void netWorkReceiver()
    {
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        filter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
        filter.addAction("android.net.wifi.STATE_CHANGE");
        mNetWorkReceiver = new NetWorkReceiver(netWorkHandler);
        registerReceiver(mNetWorkReceiver,filter);
    }


    private MyHandler netWorkHandler = new MyHandler(this);


    private static class MyHandler extends Handler{
        private WeakReference<Context> reference;
        MyHandler(Context context) {

            reference = new WeakReference<>(context);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case Constants.NetWork.IS_WIFI:
                    netWorkState = Constants.NetWork.WIFI;
                    isConnected = true;
                case Constants.NetWork.IS_MOBILE:
                    netWorkState = Constants.NetWork.MOBLIE;
                    isConnected = true;
                    EventBus.getDefault().post(new MyEvent(Constants.NetWork.ENABLE_NET,isConnected));

                    break;
                case Constants.NetWork.NO_CONNECTION:
                    isConnected = false;
                    EventBus.getDefault().post(new MyEvent(Constants.NetWork.ENABLE_NET,isConnected));
                    break;
            }
        }

    }

    public static BaseApp getInsatance() {
        return instance;
    }

    private void initBLSdk() {
        BLConfigParam blConfigParam = new BLConfigParam();
        // 1. 设置日志级别，默认为 4 全部打印
        blConfigParam.put(BLConfigParam.CONTROLLER_LOG_LEVEL, "4");
        // 2. 设置底层打印日志级别，默认为 4 全部打印
        blConfigParam.put(BLConfigParam.CONTROLLER_JNI_LOG_LEVEL, "4");

        // 3. 设置脚本保存目录, 默认在 ../let/ 目录下
        // blConfigParam.put(BLConfigParam.SDK_FILE_PATH, "");
        // 4. 设置本地控制超时时间，默认 3000ms
        blConfigParam.put(BLConfigParam.CONTROLLER_LOCAL_TIMEOUT, "10000");
        // 5. 设置远程控制超时时间，默认 5000ms
        blConfigParam.put(BLConfigParam.CONTROLLER_REMOTE_TIMEOUT, "10000");

        // 6. 设置控制重试次数，默认 1
        blConfigParam.put(BLConfigParam.CONTROLLER_SEND_COUNT, "1");
        // 7. 设置设备控制支持的网络模式，默认 -1 都支持。  0 - 局域网控制，非0 - 局域网/远程都支持。
        blConfigParam.put(BLConfigParam.CONTROLLER_NETMODE, "-1");
        // 8. 设置脚本和UI文件下载资源平台。 默认 0 老平台。  1 - 新平台
        blConfigParam.put(BLConfigParam.CONTROLLER_SCRIPT_DOWNLOAD_VERSION, "1");
        // 9. 批量查询设备在线状态最小设备数
        blConfigParam.put(BLConfigParam.CONTROLLER_QUERY_COUNT, "8");

        //连续发包次数
        blConfigParam.put(BLConfigParam.CONTROLLER_SEND_COUNT, "1");

        BLLet.init(this, blConfigParam);

        //获取lid 和licenseId ,用于其他类库的初始化
        String licenseId = BLLet.getLicenseId();
        String companyId = BLLet.getCompanyid();

        Log.i("LFX", "sdkInit: lid = " + licenseId + "   companyId =" + companyId);
        //初始化家庭库
        BLFamily.init(companyId, licenseId);
        //初始化账号库
        BLAccount.init(companyId, licenseId);

        //添加登录成功回调函数
        BLAccount.addLoginListener(BLLet.Controller.getLoginListener());
        //红外码
        BLAccount.addLoginListener(BLLet.IRCode.getLoginListener());
        //家庭
        BLAccount.addLoginListener(BLFamily.getLoginListener());
    }

    public static BLUserInfoUnits getmBLUserInfoUnits() {
        return mBLUserInfoUnits;
    }

    public static void setmBLUserInfoUnits(BLUserInfoUnits mBLUserInfoUnits) {
        BaseApp.mBLUserInfoUnits = mBLUserInfoUnits;
    }

}
